#写对象
import csv
class Student:
    def __init__(self,no,name,age,major):
        self.no = no
        self.name = name
        self.age = age
        self.major = major

stus = [
    Student("001","小明",22,"计算机科学技术"),
    Student("002","小王",23,"物联网"),
    Student("003","小刘",24,"计算机科学技术"),
    Student("004","小张",25,"汉语言文学"),
    Student("005","小曹",26,"计算机科学技术"),
    Student("006","小贝",27,"人工智能"),
]
with open("stu.csv","w",encoding="utf-8",newline="") as f:
    #写对象只能使用DictWriter
    fn = ["学号","姓名","年龄","专业"]
    writer = csv.DictWriter(f,fieldnames=fn)
    writer.writeheader()
    #需要把对象转换为字典来写,使用writerow
    #1.先要遍历
    for stu in stus:
        d = {"学号":stu.no,"姓名":stu.name,"年龄":stu.age,"专业":stu.major}
        writer.writerow(d)